<?php

namespace app\admin\controller;
use think\Controller;
use GuzzleHttp\Client;

class ApiProxy extends Controller {
	private $apikey = "A9B2B17401B5";
	private $app_id = "20231891";
	private $app_secret = "5d92eadea540354ed139ed98feda1d2a";
	private $tb_name = "%E5%B0%8F%E6%96%8C0109";
	private $tb_pid = "mm_45392257_2426700305_111599400066";

	/**
	 * 通用转链，可用于粘贴板识别转链，输入内容转链
	 * @return \think\response\Json
	 */
	public function commonAnalyze() {
		$client = new Client(['verify' => false]);
		$url    = 'https://v3.api.haodanku.com/rest';
		$data = [
			'is_change' => 1,// 是否转换口令或分享链接 0:否(默认) 1:是
			'method'    => 'analyze.clipboard', // API接口名称
			'app_id' => $this->app_id,
			'date' => date( 'Y-m-d H:i:s' ),
			'tb_name' => $this->tb_name,
			'tb_pid' => $this->tb_pid,

		];
		$data['content'] = input('content');
		$data['sign'] = $this->sign_create( $data, $this->app_secret );//生成签名
		$response = $client->request( 'POST', $url,
			[
				'json' => $data
			]
		);
		return json(json_decode($response->getBody()->getContents()));
	}

	/**
	 * 淘宝榜单
	 * @return \think\response\Json
	 */
	public function getSalesList(  ) {
		$client = new Client(['verify' => false]);
		$url = 'http://v2.api.haodanku.com/sales_list';
		$data = [
			'apikey' => $this->apikey,
			'sale_type' => '1', // 榜单类型：sale_type=1是实时销量榜（近2小时销量），type=2是今日爆单榜，type=3是昨日爆单榜，type=4是出单指数榜
		];
		$response = $client->get( $url,
			[
				'query' => $data
			]
		);
		return json(json_decode($response->getBody()->getContents()));
	}

	/**
	 * 优惠券链接转成口令
	 * @return \think\response\Json
	 */
	public function couponRatesurl() {
		$client = new Client(['verify' => false]);
		$url = 'http://v3.api.haodanku.com/coupon_ratesurl';
		$data = [
			'apikey' => $this->apikey,
			'pid' => $this->tb_pid,
		];
		$data['shop_url'] = input('shopUrl');

		$response = $client->post( $url,
			[
				'query' => $data
			]
		);
		return json(json_decode($response->getBody()->getContents()));
	}

	/**
	 * 获取商品详情
	 * @return \think\response\Json
	 */
	public function itemDetail(  ) {
		$client = new Client(['verify' => false]);
		$url = 'http://v3.api.haodanku.com/item_detail';
		$data = [
			'apikey' => $this->apikey,
			'itemid' => input('itemId'),
		];
		$response = $client->get( $url,
			[
				'query' => $data
			]
		);
		return json(json_decode($response->getBody()->getContents()));
	}



	/**
	 * 生成签名
	 *
	 * @param $data -请求数据组
	 * @param string $secret -应用密钥
	 */
	private function sign_create( &$data, $secret = '' ) {
		ksort( $data );
		$stringToBeSigned = '';
		foreach ( $data as $k => $v ) {
			if ( ! is_array( $v ) && "@" != substr( $v, 0, 1 ) ) {
				$stringToBeSigned .= "$k$v";
			}
		}
		return strtoupper( md5( $stringToBeSigned . $secret ) );
	}
}





